#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

#define BUF_SIZE 100000

char buf[BUF_SIZE] ;

void createFile()
{
    FILE *pFile = fopen("./termcap", "w") ;
    int i = 0 ;

    if (pFile == NULL)
        return ;
    for( ; i < BUF_SIZE * 2 ; i++)
        fputc('a', pFile) ;

    fclose(pFile) ;
}

void set_file_status(int fd, int flags)
{
    int val ;

    if ( (val=fcntl(fd, F_GETFL, 0)) < 0 )
        fprintf(stderr, "fcntl F_GETFL error.\n") ;

    val |= flags ;

    if ( fcntl(fd, F_SETFL, val) < 0 )
        fprintf(stderr, "fcntl F_SETFL error.\n") ;
}

void clear_file_status(int fd, int flags)
{
    int val ;

    if ( (val=fcntl(fd, F_GETFL, 0)) < 0 )
        fprintf(stderr, "fcntl F_GETFL error.\n") ;

    val &= ~flags ;

    if ( fcntl(fd, F_SETFL, val) < 0 )
        fprintf(stderr, "fcntl F_SETFL error.\n") ;
}

int main()
{
    int ntowrite, nwrite ;
    char * ptr ;

    createFile() ;

    ntowrite = read(STDIN_FILENO, buf, sizeof(buf)) ;
    fprintf(stderr, "read %d bytes.\n", ntowrite) ;

    set_file_status (STDOUT_FILENO, O_NONBLOCK ) ;

    for (ptr=buf; ntowrite > 0 ; )
    {
        errno = 0 ;
        nwrite = write(STDOUT_FILENO, ptr, ntowrite) ;
        fprintf(stderr, "\n\nnwrite=%d, errno=%d\n\n", nwrite, errno) ;

        if( nwrite > 0 )
        {
            ptr += nwrite ;
            ntowrite -= nwrite ;
        }
    }

    clear_file_status(STDOUT_FILENO, O_NONBLOCK) ;
    
    return 0 ;
}
